﻿using Microsoft.AspNetCore.Http;

namespace LowCoding.Common
{
    public class FileHelper
    {
        public class FileUploadOptions
        {
            /// <summary>
            /// 路径基地址
            /// </summary>
            public string BaseRoot { get; set; }

            /// <summary>
            /// 保存文件相对地址
            /// </summary>
            public string FileUploadPath { get; set; }

            /// <summary>
            /// 文件上传大小限制
            /// </summary>
            public string FileMaxSize { get; set; }

            /// <summary>
            /// 文件格式上传限制
            /// </summary>
            public string FileExts { get; set; }
        }

        public static Stream FileToStream(string fileName)
        {
            // 打开文件
            FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            // 读取文件的 byte[]
            byte[] bytes = new byte[fileStream.Length];
            fileStream.Read(bytes, 0, bytes.Length);
            fileStream.Close();
            // 把 byte[] 转换成 Stream
            Stream stream = new MemoryStream(bytes);
            return stream;
        }
        public static Stream Filehelper(string webRootPath, string filePath, string saveName)
        {
            return System.IO.File.Create(webRootPath + filePath + saveName);
        }

        /// <summary>
        /// 保存文件并返回文件路径
        /// </summary>
        /// <param name="files"></param>
        /// <param name="options"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public static async Task<ResponseMessageModel> Save(List<IFormFile> files, FileUploadOptions options)
        {
            List<string> fileUrls = new List<string>();
            try
            {
                string path = options.FileUploadPath + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                string root = WebHelper.ServerMapPath(path);
                if (!Directory.Exists(root))
                {
                    Directory.CreateDirectory(root);
                }
                foreach (var item in files)
                {
                    if (item == null || item.Length == 0)
                    {
                        return ToJsonTran.Fail("请选择上传的文件");
                    }
                    if (item.Length > Convert.ToInt32(options.FileMaxSize) * 1024)
                    {
                        return ToJsonTran.Fail("上传文件大小超过限制");
                    }
                    string filename = item.FileName.TrimStart('"').TrimEnd('"').Substring(item.FileName.LastIndexOf("\\") + 1);
                    string fileExt = filename.Substring(filename.LastIndexOf('.'));
                    string fileTypes = options.FileExts;
                    if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
                    {
                        return ToJsonTran.Fail("上传文件类型不正确");
                    }
                    filename = Guid.NewGuid().ToString("N") + fileExt;
                    using (var stream = new FileStream(root + filename, FileMode.Create))
                    {
                        await item.CopyToAsync(stream);
                    }
                    string fileUrl = options.BaseRoot + path + filename;
                    fileUrls.Add(fileUrl);
                }
                return ToJsonTran.Success(fileUrls);
            }
            catch (Exception ex)
            {
                return ToJsonTran.Fail(ex.Message);
            }
        }

        /// <summary>
        /// 保存文件并返回文件路径
        /// </summary>
        /// <param name="files"></param>
        /// <param name="options"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public static async Task<ResponseMessageModel> WebSave(List<IFormFile> files, FileUploadOptions options)
        {
            List<string> fileUrls = new List<string>();
            try
            {
                string path = "wwwroot/" + options.FileUploadPath + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                string root = WebHelper.ServerMapPath(path);
                if (!Directory.Exists(root))
                {
                    Directory.CreateDirectory(root);
                }
                foreach (var item in files)
                {
                    if (item == null || item.Length == 0)
                    {
                        return ToJsonTran.Fail("请选择上传的文件");
                    }
                    if (item.Length > Convert.ToInt32(options.FileMaxSize) * 1024)
                    {
                        return ToJsonTran.Fail("上传文件大小超过限制");
                    }
                    string filename = item.FileName.TrimStart('"').TrimEnd('"').Substring(item.FileName.LastIndexOf("\\") + 1);
                    string fileExt = filename.Substring(filename.LastIndexOf('.'));
                    string fileTypes = options.FileExts;
                    if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
                    {
                        return ToJsonTran.Fail("上传文件类型不正确");
                    }
                    filename = Guid.NewGuid().ToString("N") + fileExt;
                    using (var stream = new FileStream(root + filename, FileMode.Create))
                    {
                        await item.CopyToAsync(stream);
                    }
                    // options.BaseRoot
                    string fileUrl = options.FileUploadPath + "/" + DateTime.Now.ToString("yyyyMMdd") + "/" + filename;
                    fileUrls.Add(fileUrl);
                }
                return ToJsonTran.Success(fileUrls);
            }
            catch (Exception ex)
            {
                return ToJsonTran.Fail(ex.Message);
            }
        }
    }
}